package com.hyb.hybmodulessearch.controller;


import cn.easyes.core.biz.EsPageInfo;
import cn.easyes.core.conditions.LambdaEsQueryWrapper;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hyb.hybmodulessearch.domain.*;
import com.hyb.hybmodulessearch.mapper.es.ArticleMapper;
import com.hyb.hybmodulessearch.mapper.es.SearchVoMapper;
import com.ruoyi.common.core.constant.ArticleConstant;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.InnerAuth;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteSchoolRoleService;
import com.ruoyi.system.api.domain.Article;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/blob")
public class BlobSearchController {


    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    RemoteSchoolRoleService remoteSchoolRoleService;

    @InnerAuth
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Article article){
        ArticleResponseVo articleResponseVo = new ArticleResponseVo();
        BeanUtils.copyProperties(article,articleResponseVo);
        try{
            String p=redisTemplate.opsForValue().get(ArticleConstant.DESC_KEY+ SecurityUtils.getUserId());
            byte[] decode = Base64.decode(p);

            articleResponseVo.setArticleDes(decode==null?"":new String(decode).replaceAll("\n",""));

            //处理文章类型
            Long type = article.getType();
            if (type.equals(ArticleConstant.TYPE_CODE1)) {
                articleResponseVo.setType(ArticleConstant.TYPE_CODE_STRING1);
            }else if (type.equals(ArticleConstant.TYPE_CODE2)){
                articleResponseVo.setType(ArticleConstant.TYPE_CODE_STRING2);
            }else{
                articleResponseVo.setType(ArticleConstant.TYPE_CODE_STRING3);
            }

            //处理文章等级
            Long level = article.getLevel();
            if (level.equals(ArticleConstant.LEVEL_CODE0)){
                articleResponseVo.setLevel(ArticleConstant.LEVEL_STRING0);
            }else{
                articleResponseVo.setLevel(ArticleConstant.LEVEL_STRING1);
            }

            AjaxResult personalInner = remoteSchoolRoleService.getPersonalInner(SecurityConstants.INNER);
            if (personalInner.isError()){
                throw new GlobalException("获取用户认证信息异常");
            }
            Object user = personalInner.get("user");
            SchoolRole schoolRole = JSON.parseObject(JSON.toJSONString(user), SchoolRole.class);
            String college = schoolRole.getCollege();
            String major = schoolRole.getMajor();
            String label = schoolRole.getLabel();
            articleResponseVo.setSchoolRoleCollege(college==null?"":college);
            articleResponseVo.setSchoolRoleMajor(major==null?"":major);
            articleResponseVo.setSchoolRoleLabel(label==null?"":label);
            //定义用户头像
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser==null){
                throw new GlobalException("获取用户头像异常");
            }
            SysUser sysUser = loginUser.getSysUser();
            articleResponseVo.setUserAvatar(sysUser.getAvatar()==null?"":sysUser.getAvatar());
            articleMapper.insert(articleResponseVo);

            redisTemplate.delete(ArticleConstant.DESC_KEY+SecurityUtils.getUserId());
        }catch (Exception e){
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    //更新elasticSearch
    @InnerAuth
    @PostMapping("/update")
    public R<ArticleResponseVo> update(@RequestBody ArticleResponseVo articleResponseVo){
        articleMapper.updateById(articleResponseVo);
        return R.ok(articleResponseVo);
    }


    @GetMapping("/search")
    public AjaxResult search(ArticleSearchVo articleSearchVo){
        
        LambdaEsQueryWrapper<ArticleResponseVo> wrapper = new LambdaEsQueryWrapper<>();

        if (articleSearchVo.getArticleHot()==null
        && articleSearchVo.getCollectionCount()==null
        && articleSearchVo.getCommenCount()==null
        && articleSearchVo.getTrampleCount()==null
        && articleSearchVo.getDate()==null
        && articleSearchVo.getThumbCount()==null
        ){
            wrapper.orderByAsc("id");
        }
        
        if (articleSearchVo.getArticleHot()!=null){
            if (Objects.equals(articleSearchVo.getArticleHot(), ArticleConstant.ASEC_STATUS)){
                wrapper.orderByDesc("articleHot");
            }else{
                wrapper.orderByAsc("articleHot");
            }
        }

        if (articleSearchVo.getCommenCount()!=null){
            if ( articleSearchVo.getCommenCount().equals(ArticleConstant.ASEC_STATUS)){
                wrapper.orderByDesc("commenCount");
            }else{
                wrapper.orderByAsc("commenCount");
            }
        }

        if (articleSearchVo.getThumbCount()!=null){
            if ( articleSearchVo.getThumbCount().equals(ArticleConstant.ASEC_STATUS)){
                wrapper.orderByDesc("thumbCount");
            }else{
                wrapper.orderByAsc("thumbCount");
            }
        }

        if (articleSearchVo.getTrampleCount()!=null){
            if (articleSearchVo.getTrampleCount().equals(ArticleConstant.ASEC_STATUS)){
                wrapper.orderByDesc("trampleCount");
            }else{
                wrapper.orderByAsc("trampleCount");

            }
        }

        if (articleSearchVo.getDate()!=null){
            if (articleSearchVo.getDate().equals(ArticleConstant.ASEC_STATUS)){
                wrapper.orderByDesc("publishTime");
            }else{
                wrapper.orderByAsc("publishTime");
            }
        }

        if (!StringUtils.isEmpty(articleSearchVo.getContent())){
            wrapper.match(ArticleResponseVo::getArticleDes,articleSearchVo.getContent())
            .or().like("userName.keyword",articleSearchVo.getContent())
            .or().like("useNickName.keyword",articleSearchVo.getContent())
            .or().like("label.keyword",articleSearchVo.getContent())
            .or().like("type.keyword",articleSearchVo.getContent())
            .or().like("level.keyword",articleSearchVo.getContent())
            .or().like("articleTitle.keyword",articleSearchVo.getContent());
        }

        EsPageInfo<ArticleResponseVo> documentPageInfo = articleMapper.pageQuery(wrapper,articleSearchVo.getPageNum(),articleSearchVo.getPageSize());

        Map<String,Object> map=new HashMap<>();
        map.put("list",documentPageInfo.getList());
        map.put("total",documentPageInfo.getTotal());
        map.put("pages",documentPageInfo.getPages());
        return AjaxResult.success().put("map",map);
        
        
    }
}
